<template>
  <PageWrapper title="">
    <CollapseContainer title="MarkDown表单">
      <BasicForm
        :labelWidth="100"
        :schemas="schemas"
        @register="register"
        :actionColOptions="{ span: 24 }"
        :baseColProps="{ span: 24 }"
        @submit="handleSubmit"
        :submitButtonOptions="{
          text: '提交',
        }"
      />
    </CollapseContainer>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { h, onMounted, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { CollapseContainer } from '@/components/Container';
  import { useMessage } from '@/hooks/web/useMessage';
  import { MarkDown } from '@/components/Markdown';
  import { PageWrapper } from '@/components/Page';
  import {
    getAritcleApi,
    addAritcleApi,
    updateAritcleApi,
    getCategoryListApi,
  } from '@/api/hopefly/api';
  import { Article } from '@/api/hopefly/model/tableModel';

  const route = useRoute();
  // 此处可以得到用户ID
  const articleIdstr = ref(route.params?.id);
  const articleId = articleIdstr.value as unknown as number;
  const schemas: FormSchema[] = [
    {
      field: 'title',
      component: 'Input',
      label: '标题',
      defaultValue: '',
      rules: [{ required: true }],
    },
    {
      field: 'content',
      component: 'Input',
      label: '内容',
      defaultValue: '',
      rules: [{ required: true, trigger: 'blur' }],
      render: ({ model, field }) => {
        return h(MarkDown, {
          value: model[field],
          upload: {
            //更多配置请看：https://github.com/Vanessa219/vditor#options
            url: '/upload',
            fieldName: 'file',
            success: function (editor: HTMLPreElement, msg: any) {
              console.log(msg);
              const ret = JSON.parse(msg);
              editor.innerHTML += `![](${ret.result})`;
            },
          },
          onChange: (value: string) => {
            model[field] = value;
          },
        });
      },
    },
    {
      field: 'category',
      component: 'Select',
      label: '分类',
      colProps: {
        span: 8,
      },
      rules: [{ required: true }],
      componentProps: {
        options: [],
      },
    },
    {
      field: 'keywords',
      component: 'Input',
      label: '关键词',
      colProps: {
        span: 8,
      },
    },
    {
      field: 'status',
      component: 'Select',
      label: '状态',
      colProps: {
        span: 8,
      },
      defaultValue: 1,
      rules: [{ required: true }],
      componentProps: {
        options: [
          { label: '启用', value: 1 },
          { label: '禁用', value: 0 },
        ],
      },
    },
  ];
  const [register, { setFieldsValue, updateSchema }] = useForm({
    schemas,
  });
  const { createMessage } = useMessage();

  onMounted(async () => {
    const categoryList = await getCategoryListApi();
    const categoryOptions = categoryList.map((item) => ({ label: item.name, value: item.name }));
    updateSchema({
      field: 'category',
      componentProps: {
        options: categoryOptions,
      },
    });
    if (articleId === undefined) {
      return;
    }
    route.meta.title = '编辑文章';
    let data = await getAritcleApi(articleId);
    setFieldsValue({ title: data.title, content: data.content });
  });

  function handleSubmit(values: Article) {
    if (articleId === undefined) {
      addAritcleApi(values).then(() => {
        createMessage.success('添加成功');
      });
    } else {
      updateAritcleApi(articleId, values).then(() => {
        createMessage.success('更新成功');
      });
    }
  }
</script>
